﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Tools.Data;
using Tools.Models;
using Tools.Service;
using Tools.Utils;
using Tools.Web.Models;

namespace Tools.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Welcome()
        {
            return View();
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            //Image img = new Bitmap("e:/证件照/报名照片1.jpg");
            //MemoryStream stream = new MemoryStream();
            //img.Save(stream, ImageFormat.Bmp);
            //Bitmap bitmap = new Bitmap(stream);
            //new ImageService().ImageBackgroundColor(bitmap, "e:/证件照/证件照3.jpg",  Color.White,1);
            //BinaryReader br = new BinaryReader(stream);
            //photo = stream.ToArray();

            return View();
        }

        /// <summary>
        /// 特殊字符
        /// </summary>
        /// <returns></returns>
        public IActionResult Symbol()
        {
            return View();
        }

        /// <summary>
        /// 常用电话
        /// </summary>
        /// <returns></returns>
        public IActionResult Phone()
        {
            return View();
        }

        /// <summary>
        /// 国家首都
        /// </summary>
        /// <returns></returns>
        public IActionResult Nation()
        {
            return View();
        }

        /// <summary>
        /// 邮编
        /// </summary>
        /// <returns></returns>
        public IActionResult CityZipCode()
        {
            CodeService codeService = new CodeService();
            var list = codeService.GetCityZipCodeList("");
            return View(list);
        }

        /// <summary>
        /// 货币
        /// </summary>
        /// <returns></returns>
        public IActionResult Currency()
        {
            return View();
        }

        /// <summary>
        /// 图片更换背景色
        /// </summary>
        /// <returns></returns>
        public IActionResult ImageBackground()
        {
            if (Request.ContentType == null)
            {

                ViewData["message"] = "请选择上传文件";
                return View();
            }
            var formCollection = Request.Form;
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();
            var oldPath = !string.IsNullOrWhiteSpace(formCollection["OldPath"]) ? formCollection["OldPath"][0].ToString() : "";
            var colorStr = !string.IsNullOrWhiteSpace(formCollection["color"]) ? formCollection["color"][0].ToString() : "Red";
            var color = Color.Red;

            switch (colorStr)
            {
                case "Red":
                    color = Color.Red;
                    break;
                case "Blue":
                    color = Color.Blue;
                    break;
                case "White":
                    color = Color.White;
                    break;
                case "Transparent":
                    color = Color.Transparent;
                    break;
            }

            //var type = color == Color.Transparent ? "0" : "1";// Convert.ToInt32(formCollection["type"].ToString());

            if (filelist.Count() == 0 && string.IsNullOrWhiteSpace(oldPath))
            {
                ViewData["message"] = "请选择上传文件";
            }
            else
            {
                string filePath = $"{FileHelper.UploadFilePath}\\files\\images\\";
                DirectoryInfo di = new DirectoryInfo(filePath);
                if (!di.Exists) { di.Create(); }

                var url = filePath;
                var imgUrl = "";
                var isOneFile = filelist.Count == 1;

                try
                {

                    if (!string.IsNullOrWhiteSpace(oldPath))
                    {
                        string name = Path.GetFileName($"{ FileHelper.UploadFilePath}/{oldPath}");
                        string fileName = Guid.NewGuid().ToString().Replace("-", "");
                        string suffix = System.IO.Path.GetExtension(name);
                        var path = $"{url}{fileName}{suffix}";
                        imgUrl = $"/files/images/{fileName + suffix}";
                        //处理图片
                        FileStream fileStream = new FileStream($"{ FileHelper.UploadFilePath}/{oldPath}", FileMode.Open, FileAccess.Read, FileShare.Read);

                        // 读取文件的 byte[]

                        byte[] bytes = new byte[fileStream.Length];

                        fileStream.Read(bytes, 0, bytes.Length);
                        fileStream.Close();
                        // 把 byte[] 转换成 Stream
                        MemoryStream stream = new MemoryStream(bytes);
                        Bitmap bitmap = new Bitmap(stream);

                        if (string.IsNullOrWhiteSpace(oldPath))
                        {
                            var oldguid = Guid.NewGuid().ToString().Replace("-", "");
                            oldPath = $"/files/images/{oldguid}{suffix}";
                            bitmap.Save($"{FileHelper.UploadFilePath}\\files\\images\\{oldguid}{suffix}");
                        }

                        new ImageService().ImageBackgroundColor(bitmap, path, color);
                        stream.Flush();
                        stream.Dispose();

                        if (isOneFile)
                        {
                            url = path;
                        }
                    }
                    else
                    {
                        if (!isOneFile)
                        {
                            url += Guid.NewGuid().ToString().Replace("-", "");
                            new DirectoryInfo(url).Create();
                        }
                        foreach (IFormFile file in filelist)
                        {
                            string name = file.FileName;
                            string fileName = Guid.NewGuid().ToString().Replace("-", "");
                            string suffix = System.IO.Path.GetExtension(name);
                            var path = $"{url}{fileName}{suffix}";
                            imgUrl = $"/files/images/{fileName + suffix}";
                            //处理图片
                            MemoryStream stream = new MemoryStream();
                            file.CopyTo(stream);
                            Bitmap bitmap = new Bitmap(stream);

                            if (string.IsNullOrWhiteSpace(oldPath))
                            {
                                var oldguid = Guid.NewGuid().ToString().Replace("-", "");
                                oldPath = $"/files/images/{oldguid}{suffix}";
                                bitmap.Save($"{FileHelper.UploadFilePath}\\files\\images\\{oldguid}{suffix}");
                            }

                            new ImageService().ImageBackgroundColor(bitmap, path, color);
                            stream.Flush();
                            stream.Dispose();

                            if (isOneFile)
                            {
                                url = path;
                            }
                        }
                        if (!isOneFile)
                        {
                            new CompressHelper().CompressDirectory(url, $"{url}.zip", 9, false);
                        }
                    }


                    ViewData["oldPath"] = oldPath;
                    ViewData["colorStr"] = colorStr;
                    ViewData["url"] = (isOneFile || !string.IsNullOrWhiteSpace(oldPath)) ? imgUrl : $"{url}.zip";
                }
                catch (Exception ex)
                {
                    ViewData["message"] = "程序异常，请稍后重试";
                    return View();
                }
            }

            return View();
        }

        /// <summary>
        /// 证件照尺寸切换
        /// </summary>
        /// <returns></returns>
        public IActionResult ImageSize()
        {
            if (Request.ContentType == null)
            {

                ViewData["message"] = "请选择上传文件";
                return View();
            }
            var formCollection = Request.Form;
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();
            var oldPath = !string.IsNullOrWhiteSpace(formCollection["OldPath"]) ? formCollection["OldPath"][0].ToString() : "";
            var width = !string.IsNullOrWhiteSpace(formCollection["width"]) ? Convert.ToInt32(formCollection["width"][0].ToString()) : 295;
            var height = !string.IsNullOrWhiteSpace(formCollection["width"]) ? Convert.ToInt32(formCollection["width"][0].ToString()) : 413;
            var colorStr = !string.IsNullOrWhiteSpace(formCollection["color"]) ? formCollection["color"][0].ToString() : "Red";
            var color = Color.Red;

            switch (colorStr)
            {
                case "Red":
                    color = Color.Red;
                    break;
                case "Blue":
                    color = Color.Blue;
                    break;
                case "White":
                    color = Color.White;
                    break;
                case "Transparent":
                    color = Color.Transparent;
                    break;
            }

            //var type = color == Color.Transparent ? "0" : "1";// Convert.ToInt32(formCollection["type"].ToString());

            if (filelist.Count() == 0 && string.IsNullOrWhiteSpace(oldPath))
            {
                ViewData["message"] = "请选择上传文件";
            }
            else
            {
                string filePath = $"{FileHelper.UploadFilePath}\\files\\images\\";
                DirectoryInfo di = new DirectoryInfo(filePath);
                if (!di.Exists) { di.Create(); }

                var url = filePath;
                var imgUrl = "";
                var isOneFile = filelist.Count == 1;

                try
                {

                    if (!string.IsNullOrWhiteSpace(oldPath))
                    {
                        string name = Path.GetFileName($"{ FileHelper.UploadFilePath}/{oldPath}");
                        string fileName = Guid.NewGuid().ToString().Replace("-", "");
                        string suffix = System.IO.Path.GetExtension(name);
                        var path = $"{url}{fileName}{suffix}";
                        imgUrl = $"/files/images/{fileName + suffix}";
                        //处理图片
                        FileStream fileStream = new FileStream($"{ FileHelper.UploadFilePath}/{oldPath}", FileMode.Open, FileAccess.Read, FileShare.Read);

                        // 读取文件的 byte[]

                        byte[] bytes = new byte[fileStream.Length];

                        fileStream.Read(bytes, 0, bytes.Length);
                        fileStream.Close();
                        // 把 byte[] 转换成 Stream
                        MemoryStream stream = new MemoryStream(bytes);
                        Bitmap bitmap = new Bitmap(stream);

                        if (string.IsNullOrWhiteSpace(oldPath))
                        {
                            var oldguid = Guid.NewGuid().ToString().Replace("-", "");
                            oldPath = $"/files/images/{oldguid}{suffix}";
                            bitmap.Save($"{FileHelper.UploadFilePath}\\files\\images\\{oldguid}{suffix}");
                        }

                        new ImageService().ImageBackgroundColor(bitmap, path, color);
                        stream.Flush();
                        stream.Dispose();

                        if (isOneFile)
                        {
                            url = path;
                        }
                    }
                    else
                    {
                        if (!isOneFile)
                        {
                            url += Guid.NewGuid().ToString().Replace("-", "");
                            new DirectoryInfo(url).Create();
                        }
                        foreach (IFormFile file in filelist)
                        {
                            string name = file.FileName;
                            string fileName = Guid.NewGuid().ToString().Replace("-", "");
                            string suffix = System.IO.Path.GetExtension(name);
                            var path = $"{url}{fileName}{suffix}";
                            imgUrl = $"/files/images/{fileName + suffix}";
                            //处理图片
                            MemoryStream stream = new MemoryStream();
                            file.CopyTo(stream);
                            Bitmap bitmap = new Bitmap(stream);

                            if (string.IsNullOrWhiteSpace(oldPath))
                            {
                                var oldguid = Guid.NewGuid().ToString().Replace("-", "");
                                oldPath = $"/files/images/{oldguid}{suffix}";
                                bitmap.Save($"{FileHelper.UploadFilePath}\\files\\images\\{oldguid}{suffix}");
                            }

                            new ImageService().ImageBackgroundColor(bitmap, path, color);
                            stream.Flush();
                            stream.Dispose();

                            if (isOneFile)
                            {
                                url = path;
                            }
                        }
                        if (!isOneFile)
                        {
                            new CompressHelper().CompressDirectory(url, $"{url}.zip", 9, false);
                        }
                    }


                    ViewData["oldPath"] = oldPath;
                    ViewData["colorStr"] = colorStr;
                    ViewData["url"] = (isOneFile || !string.IsNullOrWhiteSpace(oldPath)) ? imgUrl : $"{url}.zip";
                }
                catch (Exception ex)
                {
                    ViewData["message"] = "程序异常，请稍后重试";
                    return View();
                }
            }

            return View();
        }

        /// <summary>
        /// 上传图片进行大小切换
        /// </summary>
        /// <param name="type">图片尺寸类型： 1-1寸；2-2寸；0-自定义</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UpdateImageSize(int type, string width, string height, string oldPath)
        {
            ResultMessage resultMessage = new ResultMessage();
            var destHeight = 0;
            var destWidth = 0;

            switch (type)
            {
                case 1:
                    destWidth = 295;
                    destHeight = 413;
                    break;

                case 2:
                    destWidth = 413;
                    destHeight = 626;
                    break;

                default:
                    try
                    {
                        destWidth = Convert.ToInt32(width.Trim());
                        destHeight = Convert.ToInt32(height.Trim());
                    }
                    catch (Exception)
                    {
                        return Json(resultMessage.Failure("填写的尺寸无效"));
                    }

                    break;
            }

            var formCollection = Request.Form;
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();

            if (filelist.Count() == 0 && string.IsNullOrWhiteSpace(oldPath))
            {
                return Json(resultMessage.Failure("请上传图片"));
            }

            string saveFilePath = $"{FileHelper.UploadFilePath}\\files\\images\\";
            DirectoryInfo di = new DirectoryInfo(saveFilePath);
            if (!di.Exists) { di.Create(); }

            var showUrl = "";

            try
            {

                if (!string.IsNullOrWhiteSpace(oldPath))
                {
                    string oldName = Path.GetFileName($"{ FileHelper.UploadFilePath}/{oldPath}");
                    string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                    string suffix = System.IO.Path.GetExtension(oldName);
                    saveFilePath = $"{saveFilePath}{newFileName}{suffix}";
                    showUrl = $"/files/images/{newFileName + suffix}";
                    //处理图片
                    FileStream fileStream = new FileStream($"{ FileHelper.UploadFilePath}/{oldPath}", FileMode.Open, FileAccess.Read, FileShare.Read);
                    byte[] bytes = new byte[fileStream.Length];

                    fileStream.Read(bytes, 0, bytes.Length);
                    fileStream.Close();

                    MemoryStream stream = new MemoryStream(bytes);
                    Bitmap bitmap = new Bitmap(stream);

                    new ImageService().ZoomImage(bitmap, destHeight, destWidth, saveFilePath);
                    stream.Flush();
                    stream.Dispose();

                }
                else
                {
                    foreach (IFormFile file in filelist)
                    {
                        string name = file.FileName;
                        string newFileName = Guid.NewGuid().ToString().Replace("-", "");
                        string suffix = System.IO.Path.GetExtension(name);
                        saveFilePath = $"{saveFilePath}{newFileName}{suffix}";
                        showUrl = $"/files/images/{newFileName + suffix}";

                        //处理图片
                        MemoryStream stream = new MemoryStream();
                        file.CopyTo(stream);
                        Bitmap bitmap = new Bitmap(stream);

                        if (string.IsNullOrWhiteSpace(oldPath))
                        {
                            var oldguid = Guid.NewGuid().ToString().Replace("-", "");
                            oldPath = $"/files/images/{oldguid}{suffix}";
                            bitmap.Save($"{FileHelper.UploadFilePath}\\files\\images\\{oldguid}{suffix}");
                        }

                        new ImageService().ZoomImage(bitmap, destHeight, destWidth, saveFilePath);
                        stream.Flush();
                        stream.Dispose();
                    }
                }

                return Json(resultMessage.Success(new { showUrl = showUrl, oldPath = oldPath, width = destWidth/2, height = destHeight/2 }));
            }
            catch (Exception ex)
            {
                return Json(resultMessage.Failure("程序异常，请稍后重试"));
            }
        }


        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
